import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';

export const useDownloadStore = defineStore('downloads', () => {
  // 从 localStorage 恢复下载状态
  const storedData = localStorage.getItem('downloads');
  const storedDownloads = storedData ? JSON.parse(storedData) : [];
  
  const downloads = ref(storedDownloads);
  
  // 添加下载任务
  const addDownload = (fileInfo) => {
    // 检查是否已存在相同ID的任务
    const existingIndex = downloads.value.findIndex(d => d.id === fileInfo.id);
    
    if (existingIndex !== -1) {
      // 重置任务状态
      downloads.value[existingIndex] = {
        ...fileInfo,
        downloadPercentage: 0,
        downloadSpeed: '0 KB/s',
        isPaused: false,
        status: 'downloading',
        chunksDownloaded: 0,
        totalChunks: 0,
        lastChunkIndex: -1
      };
      return downloads.value[existingIndex];
    }
    
    // 添加新任务
    const newDownload = {
      ...fileInfo,
      downloadPercentage: 0,
      downloadSpeed: '0 KB/s',
      isPaused: false,
      status: 'downloading',
      chunksDownloaded: 0,
      totalChunks: 0,
      lastChunkIndex: -1
    };
    
    downloads.value.push(newDownload);
    return newDownload;
  };
  
  // 更新下载进度 - 修复：使用 .value 访问
  const updateProgress = (id, progress, speed) => {
    const download = downloads.value.find(d => d.id === id);
    if (download) {
      download.downloadPercentage = Math.min(progress, 100);
      download.downloadSpeed = speed;
      
      // 自动完成检测
      if (progress >= 100) {
        download.status = 'completed';
      }
    }
  };
  
  // 暂停下载
  const pauseDownload = (id) => {
    const download = downloads.value.find(d => d.id === id);
    if (download) {
      download.isPaused = true;
      download.status = 'paused';
    }
  };
  
  // 恢复下载
  const resumeDownload = (id) => {
    const download = downloads.value.find(d => d.id === id);
    if (download) {
      download.isPaused = false;
      download.status = 'downloading';
    }
  };
  
  // 更新分片信息
  const updateChunkInfo = (id, chunkIndex, totalChunks) => {
    const download = downloads.value.find(d => d.id === id);
    if (download) {
      download.chunksDownloaded = chunkIndex + 1;
      download.lastChunkIndex = chunkIndex;
      if (totalChunks) download.totalChunks = totalChunks;
    }
  };
  
  // 完成下载
  const completeDownload = (id) => {
    const download = downloads.value.find(d => d.id === id);
    if (download) {
      download.status = 'completed';
      download.downloadPercentage = 100;
      download.isPaused = false;
    }
  };
  
  // 设置下载错误
  const setError = (id) => {
    const download = downloads.value.find(d => d.id === id);
    if (download) {
      download.status = 'error';
    }
  };
  
  // 删除下载
  const removeDownload = (id) => {
    const index = downloads.value.findIndex(d => d.id === id);
    if (index !== -1) {
      downloads.value.splice(index, 1);
    }
  };
  
  // 获取下载任务
  const getDownload = (id) => {
    return downloads.value.find(d => d.id === id);
  };
  
  // 活动中的下载任务
  const activeDownloads = computed(() => {
    return downloads.value.filter(d => d.status === 'downloading' || d.status === 'paused');
  });
  
  // 完成和错误的下载任务
  const finishedDownloads = computed(() => {
    return downloads.value.filter(d => d.status === 'completed' || d.status === 'error');
  });
  
  // 监听状态变化并保存到 localStorage
  watch(downloads, (newValue) => {
    localStorage.setItem('downloads', JSON.stringify(newValue));
  }, { deep: true });
  
  return {
    downloads,
    addDownload,
    updateProgress,
    pauseDownload,
    resumeDownload,
    updateChunkInfo,
    completeDownload,
    setError,
    removeDownload,
    getDownload,
    activeDownloads,
    finishedDownloads
  };
});